package com.zzt.service;

import com.zzt.dao.MemberinfoMapper;
import com.zzt.entity.Memberinfo;
import com.zzt.entity.MemberinfoExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailService implements UserDetailsService {
    @Resource
    MemberinfoMapper memberinfoMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MemberinfoExample example = new MemberinfoExample();
        MemberinfoExample.Criteria criteria = example.createCriteria();
        criteria.andNicknameEqualTo(username);
        List<Memberinfo> memberinfos = null;
        memberinfos = memberinfoMapper.selectByExample(example);

        String name = memberinfos.get(0).getNickname();
        String pwd = memberinfos.get(0).getPwd();
        String role = memberinfos.get(0).getPhoto();

        // 角色集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 角色必须以`ROLE_开头，数据库中没有，则在这里加
        authorities.add(new SimpleGrantedAuthority(role));

        System.out.println("角色："+memberinfos.get(0));
        if (memberinfos.size()>0) {   //数据库已经加密过了 不需要再加密了
            return new User(name, pwd,
//                    role
                    authorities
//                    AuthorityUtils.commaSeparatedStringToAuthorityList(role)
            );
        }

        else {
            throw new UsernameNotFoundException("用户\""+username+"\"不存在！");
        }
    }
}
